package com.shire.shire_interface.service.account.impl;

import com.shire.shire_interface.common.utils.FileUtils;
import com.shire.shire_interface.common.utils.JsonFormat;
import com.shire.shire_interface.common.utils.KeyValue;
import com.shire.shire_interface.constants.IphoneConfig;
import com.shire.shire_interface.constants.IphoneConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IphoneSetService {

    protected static Logger logger = LoggerFactory.getLogger(IphoneSetService.class);

    private static Map<String, IphoneConstants> _items = new HashMap<String, IphoneConstants>();
    private static Map<String, String> _version_build = new HashMap<String, String>();
    private static Map<String, IphoneConfig> _config_map = new HashMap<String, IphoneConfig>();

    @PostConstruct
    public void init(){
        load();
    }

    public void load() {
        try {
            Map<String, IphoneConstants> tmp_items = new HashMap<String, IphoneConstants>();
            Map<String, String> tmp_version_build = new HashMap<String, String>();

            String content = FileUtils.readFileToString(this.getClass().getResourceAsStream("/iphoneset/iphone_constants.json")).toString();
//			logger.info("content = " + content);
            Map<String, Object> map = JsonFormat.toMap(content);
            List<Map<String, Object>> items = (List<Map<String,Object>>)map.get("items");
            for(Map<String, Object> item : items){
                try{
                    String name = (String)item.get("name");
                    List<Map<String, Object>> infos = (List<Map<String, Object>>)item.get("infos");
                    tmp_items.put(name, new IphoneConstants(name, infos));
                }
                catch(Exception e){}
            }

            Map<String, Object> versions = (Map<String, Object>)map.get("versions");
            for(Map.Entry<String, Object> entry : versions.entrySet()){
                tmp_version_build.put(entry.getKey(), (String)entry.getValue());
            }
            _items = tmp_items;
            _version_build = tmp_version_build;
        } catch (Exception e) {
            logger.error("载入iphoneSet配置异常：", e);
        }
    }

    public IphoneParameter getRandomParameter(String configName){
        try {
//			String workEnv = systemVariablesService.getVariablesValue("work.env", "");
//			if(workEnv.equals("test") && deviceInfo.getGroupId()!=null && deviceInfo.getGroupId()<10){
//				DeviceGroup group = getByCache(DeviceGroup.class, deviceInfo.getGroupId());
//				if(StrUtils.getNullStr(group.getSite()).startsWith("plus11")){
//					return new IphoneParameter("spc_iPhone7Plus", "iPhone9,2", "11.3.1", "A1785", "15E302");
//				}
//				else if(StrUtils.getNullStr(group.getSite()).startsWith("plus10")){
//					return new IphoneParameter("spc_iphone8plus", "iPhone10,2", "10.3.3", "A1864", "14G60");
//				}
//				else if(StrUtils.getNullStr(group.getSite()).startsWith("normal11")){
//					return new IphoneParameter("spc_iPhone7", "iPhone9,1", "11.2.5", "A1780", "15D60");
//				}
//				else{
//					return new IphoneParameter("spc_iphone5s", "iPhone6,1", "10.3.3", "A1533", "14G60");
//				}
//			}
            IphoneConfig iphoneConfig = getConfig(configName);
            if(iphoneConfig==null){
                iphoneConfig = getConfig("default");
            }
            if(iphoneConfig!=null){
                KeyValue<String, String> kv = iphoneConfig.getRandomConfig();
                if(kv!=null){
                    IphoneParameter iphoneParameter = new IphoneParameter();
                    iphoneParameter.setName(kv.getKey());
                    iphoneParameter.setOsversion(kv.getValue());
                    IphoneConstants iphoneConstants = _items.get(kv.getKey());
                    if(iphoneConstants!=null){
                        KeyValue<String, String> platform_model = iphoneConstants.getInfo();
                        iphoneParameter.setPlatform(platform_model.getKey());
                        iphoneParameter.setModel(platform_model.getValue());
                        iphoneParameter.setBuildVersion(_version_build.get(kv.getValue()));
                        return iphoneParameter;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new IphoneParameter("ex_iphone8plus", "iPhone10,2", "10.3.3", "A1864", "14G60");
    }

    private IphoneConfig getConfig(String configName){
        try {
            synchronized (configName.intern()) {
                IphoneConfig iphoneConfig = _config_map.get(configName);
                if(iphoneConfig!=null) return iphoneConfig;
                iphoneConfig = new IphoneConfig();
                URL url = IphoneSetService.class.getClassLoader().getResource("iphoneset/iphone_cfg_"+configName+".json");
                String path = url.getPath();
                String content = FileUtils.readFileToString(this.getClass().getResourceAsStream("/iphoneset/iphone_cfg_"+configName+".json")).toString();
                Map<String, Object> map = JsonFormat.toMap(content);
                boolean rst = iphoneConfig.init(configName, map);
                if(rst){
                    _config_map.put(configName, iphoneConfig);
                    return iphoneConfig;
                }
            }
        } catch (Exception e) {
            logger.error("载入配置文件异常[configName="+configName+"]：", e);
        }
        return null;
    }

    public static void main(String[] args){
        System.out.println("-----------------------------S");
        IphoneSetService is = new IphoneSetService();
        is.load();
        for(int i=0; i<100; i++){
            IphoneParameter ip = is.getRandomParameter("default");
            System.out.println(ip);
        }
        IphoneConfig config = is.getConfig("default");
        config.testRate();
        System.out.println("-----------------------------E");
    }
}
